package com.wbl.train.business.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.wbl.train.business.service.DailySkTokenService;
import com.wbl.train.common.business.dto.SkTokenDto;
import com.wbl.train.common.business.entity.SkTokenEntity;
import com.wbl.train.common.exception.ApplicationException;
import com.wbl.train.common.page.PageVo;
import com.wbl.train.common.result.R;
import com.wbl.train.common.result.ResultCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 王博纶
 * @since 2024-05-26
 * @description 秒杀令牌
 */
@Slf4j
@RestController
@RequestMapping("/admin/sk-token")
@Tag(name = "秒杀令牌控制器类",
        description = "SkTokenController 秒杀令牌 后端数据接口")
public class SkTokenAdminController {
    @Autowired
    private DailySkTokenService dailySkTokenService;

    /**
     * 通过id查询 秒杀令牌
     * @param skTokenDto skTokenDto
     * @return Result
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/query")
    public R<PageVo<SkTokenEntity>> getById(SkTokenDto skTokenDto) {
        // 火车每日车次查询
        log.debug("skTokenDto :{}",skTokenDto);
        PageVo<SkTokenEntity> pageVo = dailySkTokenService.querySKToken(skTokenDto);
        return R.ok("查询成功",pageVo);
    }

    /**
     * 新增 秒杀令牌
     * @param skToken 秒杀令牌
     * @return Result
     */
    @Operation(summary = "新增秒杀令牌", description = "新增秒杀令牌")
    @PostMapping("/save")
    public R<Boolean> save(@Valid @RequestBody SkTokenEntity skToken) {
        return R.ok("保存成功",dailySkTokenService.insertAndUpdateSKToken(skToken));
    }


    /**
     * 通过id删除 秒杀令牌
     * @param id id
     * @return Result
     */
    @Operation(summary = "删除秒杀令牌",
            description = "删除秒杀令牌")
    @DeleteMapping("/delete/{id}")
    public R<Boolean> removeById(@PathVariable Long id) {
        if(ObjectUtil.isNull(dailySkTokenService.getById(id))){
            throw new ApplicationException(ResultCode.DATA_NOT_EXIST,"令牌不存在");
        }
        return R.ok(dailySkTokenService.removeById(id));
    }

    /**
     * 根据实际情况生成每日的令牌余量
     * @param skTokenDto skTokenDto
     */
    @Operation(summary = "生成令牌数量",
            description = "生成令牌数量")
    @DeleteMapping("/gen-sk-token")
    public void genSKToken(SkTokenDto skTokenDto) {
        log.info("火车【{}】的令牌数量生成开始",skTokenDto.getTrainCode());
        dailySkTokenService.genDaily(skTokenDto.getDate(), skTokenDto.getTrainCode());
        log.info("火车【{}】的令牌数量生成结束",skTokenDto.getTrainCode());
    }
}
